<script setup>
	import {
		ref
	} from 'vue';
	import dayjs from "dayjs"

	const pictures = ref([]);
	const uploadFileObj = uniCloud.importObject("uploadFileObj");
	//{	temp: "",fileID: "",url: "",status: 2,progress: 0	}
	// 选择图像
	const selectPic = async () => {
		let file = await uni.chooseImage({
			count: 1
		})

		pictures.value = file.tempFilePaths.map(item => ({
			temp: item,
			status: 0,
			progress: 0
		}))
		// 文件夹名
		let filename = dayjs().format("YYYYMMDD") + "/" + Date.now() + ".jpg";
		// 状态改变
		pictures.value[0].status = 1;
		let cloud = await uniCloud.uploadFile({
			filePath: pictures.value[0].temp, //本地临时地址
			cloudPath: filename, //云端路径
			// 上传进度
			onUploadProgress: event => {
				pictures.value[0].progress = Math.round(
					(event.loaded * 100) / event.total
				);
			}
		})
		// 状态改变（成功
		pictures.value[0].status = 2;

		let path = cloudToHttps(cloud.fileID);
		
		pictures.value[0].fileID = cloud.fileID;
		pictures.value[0].url = path;
		
		console.log(pictures.value);

	}

	// 关闭
	const handleClose = () => {
		// 根据fileID删除图片
		uploadFileObj.remove([pictures.value[0].fileID])
			.then(res => {
				console.log(res);
			})
		pictures.value = [];
	}


	const cloudToHttps = (str) => {
		// 1 把"cloud://"换成 "https://"
		return str.replace("cloud://", "https://")
			//2 str.split("/")[2]换成str.plit("/")[2] + ".normal.cloudstatic.cn"
			.replace(str.split("/")[2], str.split("/")[2] + ".normal.cloudstatic.cn");
	}
</script>
<template>
	<view class="layout">
		<view class="picGroup">
			<view class="box add" @click="selectPic" v-if="pictures.length==0">+</view>

			<view class="box" v-for="item,index in pictures" :key="index">

				<image :src="item.temp" mode="aspectFill"></image>
				<!-- 关闭按钮 -->
				<view class="close" @click="handleClose">×</view>
				<!-- 进度条 -->
				<view class="mask" v-if="item.status == 1">{{item.progress}}%</view>
			</view>
		</view>

	</view>
</template>
<style lang="scss" scoped>
	.layout {
		padding: 30rpx;

		.picGroup {
			display: grid;
			grid-template-columns: repeat(3, 1fr);
			gap: 20rpx;

			.box {
				width: 100%;
				aspect-ratio: 1 / 1;
				position: relative;

				image {
					width: 100%;
					height: 100%;
					display: block;
				}

				.close {
					position: absolute;
					top: 10rpx;
					right: 10rpx;
					width: 60rpx;
					height: 60rpx;
					background: rgba(0, 0, 0, 0.6);
					color: #fff;
					border-radius: 50%; //圆角
					border: 1px solid #fff;
					display: flex; //居中
					align-items: center;
					justify-content: center;
				}

				.mask {
					position: absolute;
					top: 0;
					left: 0;
					width: 100%;
					height: 100%;
					background: rgba(0, 0, 0, 0.6);
					color: #fff;
					display: flex;
					align-items: center;
					justify-content: center;
				}
			}

			.add {
				background: #eee;
				font-size: 90rpx;
				color: #333;
				// 居中
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}

	}
</style>